﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Noebe.Orm;
using Pixysoft.Framework.Security.Entity;
using System.Web;

namespace Pixysoft.Framework.Security.Controller
{
    class OrmController
    {
        /// <summary>
        /// 根据用户名查询数据库取得user
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static User GetUser(string name)
        {
            if (name == null || name.Trim() == "")
                return null;

            return OrmManager.Instance.GetQuery().SelectByUpk<User>(name);
        }

        /// <summary>
        /// 忽略动作查看权限
        /// </summary>
        /// <param name="user"></param>
        /// <param name="resName"></param>
        /// <returns></returns>
        public static bool ResourceAuthorizing(User user, string resName)
        {
            IOrmRightQuery<User> query = OrmManager.Instance.GetRightQuery<User>();
            query.QueryString = "user.roleList.PermissionList.ResList = :VALUE";
            query.Parameters.Add("VALUE", resName);
            query.OrmObject = user;
            List<string> list = query.Select<string>();
            return list.Count > 0;
        }

        /// <summary>
        /// 权限的验证
        /// </summary>
        /// <param name="user"></param>
        /// <param name="permissionName"></param>
        /// <returns></returns>
        public static bool PermissionAuthorizing(User user, string permissionName)
        {
            IOrmRightQuery<User> query = OrmManager.Instance.GetRightQuery<User>();
            query.QueryString = "user.roleList.PermissionList.PermissionName = :VALUE";
            query.Parameters.Add("VALUE", permissionName);
            query.OrmObject = user;
            return query.Select<string>().Count > 0;
        }


        /// <summary>
        /// 验证对象是否有页面请求目标的使用权限
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="handler">The handler.</param>
        /// <returns></returns>
        public static bool ObjectAuthorizing(UserInfo principal, HttpRequest req)
        {
            User user = OrmManager.Instance.GetQuery().SelectByUpk<User>(principal.Name);

            if (user == null)
                return false;

            string fileName = Pixysoft.Web.UrlHelper.Instance.GetUrlFileName(req);

            return OrmController.ResourceAuthorizing(user, fileName);
        }
    }
}
